package jch.learn.java.basics.chapter14;

import jch.learn.java.basics.chapter14.unsynch.Bank;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockBank extends Bank {

    // 可重入锁 | public class ReentrantLock implements Lock, java.io.Serializable
    private Lock bankLock;
    private Condition sufficientFunds;

    /**
     * 银行构造器
     *
     * @param n              账户数量
     * @param initialBalance 账户初始化余额
     */
    public ReentrantLockBank(int n, double initialBalance) {
        super(n, initialBalance);
        this.bankLock = new ReentrantLock();
        this.sufficientFunds = bankLock.newCondition();
    }

    @Override
    public void transfer(int from, int to, double amount) {
        bankLock.lock();
        try {
            super.transfer(from, to, amount);
            sufficientFunds.signalAll();
        } finally {
            bankLock.unlock();
        }
    }

    @Override
    public double getTotalBalance() {
        bankLock.lock();
        try {
            return super.getTotalBalance();
        } finally {
            bankLock.unlock();
        }
    }
}
